#!/usr/bin/env zx
const { readJsonSync, appendFile } = require('fs-extra')

const apkPath =
  '/Users/zjr/Desktop/yiren/jack_android/android/app/release/app-release.apk'
// const adbPath = '/Users/zjr/Library/Android/sdk/platform-tools/adb'
const padipPath = '/Users/zjr/Desktop/yiren/jack-pad/ssh/padipdier.json'

// 读取 padip.json 文件
const padipData = readJsonSync(padipPath)
console.log(padipData.device)
// 遍历所有设备并执行 adb 命令
for (const device of padipData.device) {
  const msg = `Updating APK on device ${device.name} (${device.ipAddress})\n`
  console.log(msg)
  try {
    await $`adb connect ${device.ipAddress}`
    // await $`adb uninstall com.testrn`
    await $`adb -s ${device.ipAddress}:5555 install -r "${apkPath}"`
    await $`adb shell am start com.testrn/.MainActivity`
    await $`adb disconnect ${device.ipAddress}`
    await appendFile('updata.log', msg)
  } catch (error) {
    await appendFile(
      'updata.log',
      `${device.name}-${device.ipAddress}: ${error}\n`
    )
  }
}

const successMsg = 'APK update completed successfully!\n'
console.log(successMsg)
await appendFile('updata.log', successMsg)
